<?php

class client
{
    protected $ip;
    protected $port;

    public function __construct($ip, $port)
    {
        $this->ip = $ip;
        $this->port = $port;
        $this->createClient();
    }

    private function createClient()
    {
        //创建socket资源
        $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($sock < 0) {
            echo "error:" . socket_strerror(socket_last_error()) . "\n";
        }

        //连接
        $ret = socket_connect($sock, $this->ip, $this->port);
        if (!$ret) {
            echo "bind failed:" . socket_strerror(socket_last_error()) . "\n";
            exit;
        }
        echo "客户端准备就绪\n";

        $msg = "abcd";
        socket_write($sock, $msg, strlen($msg));

        $buf = socket_read($sock, 1024);
        if (!$buf) {
            echo "read failed:" . socket_strerror(socket_last_error()) . "\n";
        }
        $msg = "服务器端返回的数据 $buf\n";
        echo $msg;
        socket_close($sock);
    }

}

$client = new client("127.0.0.1", 8116);